from PIL import Image
import os

def crop_image_by_coords(input_path, output_path, left, top, right, bottom):
    """
    根据坐标裁剪图片
    :param input_path: 输入图片路径
    :param output_path: 输出图片路径
    :param left: 左上角x坐标
    :param top: 左上角y坐标
    :param right: 右下角x坐标
    :param bottom: 右下角y坐标
    """
    try:
        # 打开图片
        with Image.open(input_path) as img:
            # 确保坐标有效
            width, height = img.size
            left = max(0, min(left, width))
            top = max(0, min(top, height))
            right = max(left, min(right, width))
            bottom = max(top, min(bottom, height))
            
            # 裁剪图片
            # resize to 224x224
            cropped_img = img.resize((600, 300))
            # cropped_img = img.crop((left, top, right, bottom))
            # 保存裁剪后的图片
            cropped_img.save(output_path)
            print(f"图片已成功裁剪并保存至: {output_path}")
            return True
    except Exception as e:
        print(f"裁剪失败: {str(e)}")
        return False

if __name__ == "__main__":
    # 示例用法
    input_image = "/home/one/Pictures/600.png"    # 输入图片路径
    output_dir = "./cropped_images.png"  # 输出目录
    
    # 示例1: 按坐标裁剪 (左上角(100, 100)，右下角(400, 300))
    crop_image_by_coords(
        input_image,
        output_dir,
        left=0,
        top=0,
        right=600,
        bottom=300
    )